package com.chatmcp.mcprouter.service.impl;

import com.chatmcp.mcprouter.dto.ProxyInfoDto;
import com.chatmcp.mcprouter.service.ProxyInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 代理信息服务实现类
 * 负责存储和检索代理会话信息
 */
@Slf4j
@Service
public class ProxyInfoServiceImpl implements ProxyInfoService {

    private final ObjectMapper objectMapper;
    private final RedisTemplate<String, String> redisTemplate;
    
    // 如果Redis不可用，使用本地缓存
    private final Map<String, ProxyInfoDto> localCache = new ConcurrentHashMap<>();
    
    // 缓存过期时间（秒）
    private static final long CACHE_EXPIRATION = 24 * 60 * 60; // 24小时
    
    // 缓存键前缀
    private static final String CACHE_KEY_PREFIX = "proxy_info:";

    @Autowired
    public ProxyInfoServiceImpl(ObjectMapper objectMapper, RedisTemplate<String, String> redisTemplate) {
        this.objectMapper = objectMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean storeProxyInfo(String sessionId, ProxyInfoDto proxyInfo) {
        if (sessionId == null || proxyInfo == null) {
            return false;
        }
        
        try {
            // 尝试存储到Redis
            String key = CACHE_KEY_PREFIX + sessionId;
            String value = objectMapper.writeValueAsString(proxyInfo);
            
            boolean redisSuccess = false;
            try {
                redisTemplate.opsForValue().set(key, value, CACHE_EXPIRATION, TimeUnit.SECONDS);
                redisSuccess = true;
            } catch (Exception e) {
                log.warn("Failed to store proxy info in Redis: {}", e.getMessage());
            }
            
            // 如果Redis存储失败，存储到本地缓存
            if (!redisSuccess) {
                localCache.put(sessionId, proxyInfo);
            }
            
            return true;
        } catch (Exception e) {
            log.error("Failed to store proxy info: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public ProxyInfoDto getProxyInfo(String sessionId) {
        if (sessionId == null) {
            return null;
        }
        
        try {
            // 先尝试从Redis获取
            String key = CACHE_KEY_PREFIX + sessionId;
            String value = null;
            
            try {
                value = redisTemplate.opsForValue().get(key);
            } catch (Exception e) {
                log.warn("Failed to get proxy info from Redis: {}", e.getMessage());
            }
            
            if (value != null) {
                return objectMapper.readValue(value, ProxyInfoDto.class);
            }
            
            // 如果Redis获取失败，从本地缓存获取
            return localCache.get(sessionId);
        } catch (Exception e) {
            log.error("Failed to get proxy info: {}", e.getMessage());
            return null;
        }
    }

    @Override
    public boolean deleteProxyInfo(String sessionId) {
        if (sessionId == null) {
            return false;
        }
        
        try {
            // 尝试从Redis删除
            String key = CACHE_KEY_PREFIX + sessionId;
            
            try {
                redisTemplate.delete(key);
            } catch (Exception e) {
                log.warn("Failed to delete proxy info from Redis: {}", e.getMessage());
            }
            
            // 从本地缓存删除
            localCache.remove(sessionId);
            
            return true;
        } catch (Exception e) {
            log.error("Failed to delete proxy info: {}", e.getMessage());
            return false;
        }
    }
} 